package com.imooc.utils;

import com.imooc.exceptions.GraceException;
import com.imooc.grace.result.ResponseStatusEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;

@Component
@Slf4j
public class JWTUtils {

    public static final String at = "@";

//    @Autowired
//    private JWTProperties jwtProperties;

    @Value("${jwt.key}")
    private String JWT_KEY;

    public String createToken(String body, String prefix) {
        return prefix + at + dealToken(body, null);
    }

    public String createToken(String body, Long expireTimes, String prefix) {
        if (expireTimes == null) {
            GraceException.display(ResponseStatusEnum.SYSTEM_NO_EXPIRE_ERROR);
        }

        return prefix + at + dealToken(body, expireTimes);
    }

    public String createToken(String body) {
        return dealToken(body, null);
    }

    public String createToken(String body, Long expireTimes) {
        if (expireTimes == null) {
            GraceException.display(ResponseStatusEnum.SYSTEM_NO_EXPIRE_ERROR);
        }

        return dealToken(body, expireTimes);
    }

    public String checkJWT(String pendingJWT) {
        String userKey = JWT_KEY;

        // 1. 使用Java标准库进行Base64编码（替换弃用API）
        byte[] keyBytes = userKey.getBytes(StandardCharsets.UTF_8);  // 明确指定编码
        String base64 = Base64.getEncoder().encodeToString(keyBytes);

        // 2. 生成密钥对象
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes(StandardCharsets.UTF_8));

        JwtParser jwtParser = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build();
        Jws<Claims> jws = jwtParser.parseClaimsJws(pendingJWT);
        return jws.getBody().getSubject(); // userJson
    }

    private String dealToken(String body, Long expireTimes) {
        String userKey = JWT_KEY;
//        log.error("userKey:{}", userKey);

        // 1. 使用Java标准库进行Base64编码（替换弃用API）
        byte[] keyBytes = userKey.getBytes(StandardCharsets.UTF_8);  // 明确指定编码
        String base64 = Base64.getEncoder().encodeToString(keyBytes);

        // 2. 生成密钥对象
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes(StandardCharsets.UTF_8));

        // 3. 动态生成JWT
        String jwt = (expireTimes != null) ?
                generateToken(body, expireTimes, secretKey) :
                generateToken(body, secretKey);

        log.info("JWT: {}", jwt);
        return jwt;
    }

    private String generateToken(String body, SecretKey secretKey) {
        return Jwts.builder()
                .setSubject(body)    // 设置自定义数据
                .signWith(secretKey)   // 使用哪个密钥对象
                .compact();
    }

    private String generateToken(String body, Long expireTimes, SecretKey secretKey) {
        Date date = new Date(System.currentTimeMillis() + expireTimes);
        return Jwts.builder()
                .setSubject(body)
                .signWith(secretKey)
                .setExpiration(date)
                .compact();
    }
}
